package priv.lhy.ecm.analysis.service;

import priv.lhy.common.abs.AbstractRequest;
import priv.lhy.common.abs.AbstractResponse;
import priv.lhy.common.utils.DateUtil;
import priv.lhy.ecm.analysis.constants.TableInfo;
import priv.lhy.ecm.analysis.mapper.AbsMapper;

import java.lang.reflect.ParameterizedType;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: lihy
 * date: 2019/7/4 10:45
 * description:
 */
public abstract class AbsService<T> implements IService<T> {

    private String tablePrefix;

    private AbsMapper<T> mapper;

    public AbsService(AbsMapper<T> mapper) {
        this.mapper = mapper;
        Class<T> clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
                .getActualTypeArguments()[0];
        tablePrefix = TableInfo.tableNamePrefix.get(clazz);
    }

    @Override
    public abstract AbstractResponse selectByTime(AbstractRequest request);

    public List<T> doSelect(int companyCode, String showColumns, String begin, String end) throws
            ParseException {

        List<T> result = new ArrayList<>();
        List<String> tableNameSuffixs = DateUtil.interval(begin, end);
        for (String suffix : tableNameSuffixs) {
            List<T> list = mapper.selectByTime(tablePrefix + "_" + companyCode + "_" + suffix,
                    showColumns, begin, end);
            if (null != list && list.size() > 0) {
                result.addAll(list);
            }
        }

        return result;
    }
}
